package org.jeecg.modules.demo.hd.job;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.demo.hd.entity.AppTeamCommissionDetail;
import org.jeecg.modules.demo.hd.service.IAppTeamCommissionDetailService;
import org.jeecg.modules.demo.hd.service.IAppUserGoldDetailService;
import org.jeecg.modules.demo.hd.service.IAppUserGoldMainService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 每日凌晨1点发放上一天推广用户的提成奖励
 *
 * @author sutao
 */
@Slf4j
public class CommissionDistributionTaskJob implements Job {

    @Resource
    private IAppUserGoldDetailService userGoldDetailService;

    @Resource
    private IAppUserGoldMainService userGoldMainService;

    @Resource
    private ISysUserService userService;

    @Resource
    private IAppTeamCommissionDetailService commissionDetailService;

    /**
     * 统计上一日每人获得金币总量（点广激励金币）
     * 查找上级用户，获得分佣比例和分佣类型
     * 判断用户是否重复分佣
     * 添加分佣明细表， 时间、分佣类型、分佣比例、下级用户ID、下级用户获得金币总额、分佣金额、状态、奖励用户ID
     * 按照奖励用户ID，合并统计奖励金额，发放到金币明细表。
     *
     * @param jobExecutionContext
     * @throws JobExecutionException
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //查询所有用户ID
        List<SysUser> list = userService.list();
        // 昨天日期
        LocalDate localDate = DateUtils.getLocalDate().minusDays(1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");  // 定义日期格式
        String day = localDate.format(formatter);  // 格式化昨天的日期
        List<AppTeamCommissionDetail> detailList = new ArrayList<>();
        for (SysUser user : list) {
            if (StringUtils.isEmpty(user.getParentUser())) {
                continue;
            }
            // 获取用户昨天的 点广奖励金币
            Double goldNum = userGoldDetailService.quereUserGoldTotalByDay(day, user.getId());
            if (ObjectUtils.isNotNull(goldNum) && goldNum > 0) {
                System.out.println("" + user.getId() + ":::::::" + goldNum);
                // 查找用户的上级用户
                Optional<SysUser> parentUserOpt = list.stream().filter(item -> user.getParentUser().equals(item.getGenCode())).findFirst();
                if (parentUserOpt.isPresent()) {
                    SysUser parentUser = parentUserOpt.get();
                    double teamRate = parentUser.getTeamCommissionRate();
                    if (teamRate == 0d || teamRate > 0.1d) {
                        teamRate = 0.1d;
                    }
                    double tearGoldNum = goldNum * teamRate;
                    // 奖励类型
                    String teamCommissionType = parentUser.getTeamCommissionType();
                    // 添加团队奖励明细
                    AppTeamCommissionDetail commissionDetail = new AppTeamCommissionDetail();
                    commissionDetail.setCommissionDay(new Date());
                    commissionDetail.setGoldNum(tearGoldNum);
                    commissionDetail.setCommissionType(teamCommissionType);
                    commissionDetail.setTeamRate(teamRate);
                    commissionDetail.setParentUser(parentUser.getId());
                    commissionDetail.setUserId(user.getId());
                    commissionDetail.setOrgCode(user.getOrgCode());
                    commissionDetailService.insert(commissionDetail);
                    detailList.add(commissionDetail);

                }
            }
        }
        //
        List<String> tuanduizhangIds = Arrays.asList("1921511612346699777", "");

        //所有用户统计完后，合并统计生成金币明细
        List<String> userList = detailList.stream().map(item -> item.getParentUser()).distinct().collect(Collectors.toList());
        for (String _userId : userList) {
            double goldSum = 0d;
            // 部门负责人的团队奖励  查询部门下所有人员团队奖励；这里部门写死
            if (tuanduizhangIds.contains(_userId)) {
                if (_userId.equals("1921511612346699777")) {
                    goldSum = detailList.stream().filter(i -> "A03".equals(i.getOrgCode())).mapToDouble(AppTeamCommissionDetail::getGoldNum).sum();
                    goldSum += detailList.stream().filter(i -> "1919332301380452353".equals(i.getOrgCode())).mapToDouble(AppTeamCommissionDetail::getGoldNum).sum();
                }
            } else {
                goldSum = detailList.stream().filter(i -> i.getParentUser().equals(_userId)).mapToDouble(AppTeamCommissionDetail::getGoldNum).sum();
            }
            goldSum *= 1;
            Optional<AppTeamCommissionDetail> first = detailList.stream().filter(item -> item.getParentUser().equals(_userId)).findFirst();
            if (first.isPresent()) {
                if (StringUtils.isEmpty(first.get().getCommissionType()))
                    first.get().setCommissionType("1");
                userGoldDetailService.commissionGold(_userId, goldSum, first.get().getCommissionType().equals("1") ? "4" : "5");
            }
        }
        System.out.println("执行提成奖励定时任务");
    }
}
